<?php
/**
 * @file log.class.php
 * @author 禅元天道 chanyuantiandao@126.com
 * @DateTime 2022-01-22 13:02
 * @brief TODO
 */

!defined('CHAN_CMS') && exit('非法访问！');

class Log
{
    private static $_instance = null;
    private $config = array();
    private $path = '';

    public static function getInstance($config)
    {
        if(is_null(self::$_instance) || !self::$_instance instanceof self){
            self::$_instance = new self($config);
        }
        return self::$_instance;
    }

    private function __construct($config){
        $this->config = $config;
        $this->path = FileHelper::joinPathWithRoot($this->config['path']);
        if(!is_dir($this->path) && !mkdir($this->path, 0666, true)){
            $this->info('创建日志目录'.$this->path.'失败！');
            throw new ChanException('创建日志目录'.$this->path.'失败！');
        }
    }

    public function error($message, $type = '', $level = '', $file = '', $line = ''){
        $content = '错误信息['.date('Y-m-d H:i:s').']：'."\n";
        $content .= '错误类型：'.$type.' 错误等级:'.$level.']'."\n";
        $content .= '错误信息：'.$message."\n";
        if(!empty($file) && !empty($line))
            $content .= '文件位置：'.str_replace(ROOT_DIRECTORY, '', $file).':'.$line."\n";
        $content .= '请求信息：http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]."\n\n";
        file_put_contents($this->path.date('Ymd').'_error.php', $content, FILE_APPEND);
    }

    public function info($message){
        $content = '['.date('Y-m-d H:i:s').']';
        $content .= '用户('.getClientIP().')';
        $content .= $message;
        $content .= "\n";
        if(!file_put_contents($this->path.date('Ymd').'_info.php', $content, FILE_APPEND)){
            exit('写入日志失败！');
        }
    }

    public function user($message){
        $content = '['.date('Y-m-d H:i:s').']';
        $content .= '用户('.getClientIP().')';
        $content .= $message;
        $content .= "\n";
        if(!file_put_contents($this->path.date('Ymd').'_log.php', $content, FILE_APPEND)){
            exit('写入日志失败！');
        }
    }

    private function __clone(){}

    function __destruct() {
    }
}